package com.lbn.baseframe.net.business;


import com.google.gson.Gson;
import com.lbn.baseframe.utils.L;

import okhttp3.ResponseBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/8/15.
 */
public class RxHelper {


    public static <T> Observable.Transformer<BaseModel<T>, T> handleResult() {
        return new Observable.Transformer<BaseModel<T>, T>() {
            @Override
            public Observable<T> call(Observable<BaseModel<T>> baseModelObservable) {
                return baseModelObservable.flatMap(new Func1<BaseModel<T>, Observable<T>>() {
                    @Override
                    public Observable<T> call(BaseModel<T> tBaseModel) {

                        /**
                         * 处理业务逻辑
                         */
                        if(tBaseModel.code==0){
                            L.e("tBaseModel:"+new Gson().toJson(tBaseModel));
                            return createData(tBaseModel.data);
                        }else{
                            if (tBaseModel.msg!=null){
                                return Observable.error(new Exception(tBaseModel.msg));
                            }

                        }

//                        if (tBaseModel.code == 200) {
//
//                            if (tBaseModel.ret == null) {
//                                return Observable.error(new Exception(Constants.ERROR_NULL));
//                            }
//
//                            return createData(tBaseModel.ret);
//                        }
////                        else if(tBaseModel.retCode == 10001){
////                            App.loginFailure(tBaseModel.retMsg);
////                        }
//                        else if (tBaseModel.retCode == 4002) {
//                            return Observable.error(new Exception(String.valueOf(tBaseModel.retCode)));
//                        } else {
//                            return Observable.error(new Exception(tBaseModel.retMsg));
//                        }
//                        return null;

                        return Observable.error(new Exception(tBaseModel.msg));
                    }
                });
            }
        };
    }


    private static <T> Observable<T> createData(final T data) {
        return Observable.create(new Observable.OnSubscribe<T>() {

            @Override
            public void call(Subscriber<? super T> subscriber) {
                try {
                    subscriber.onNext(data);
                    subscriber.onCompleted();
                } catch (Exception e) {
//                    L.e("error:"+e.getClass());
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        });
    }
}
